package com.xiashitech.agent.diagnosis.util;

import com.fasterxml.jackson.databind.ObjectMapper;

public class DiagnosisJsonUtil {
    public static boolean isJson(String jsonString) {
        boolean isValid = false;
        try{
            if (jsonString != null && !"".equals(jsonString.trim())) {
                jsonString = jsonString.trim();
                if (jsonString.startsWith("{") && jsonString.endsWith("}")) {
                    new ObjectMapper().readTree(jsonString);
                    isValid = true;
                } else if (jsonString.startsWith("[") && jsonString.endsWith("]")) {
                    new ObjectMapper().readTree(jsonString);
                    isValid = true;
                }
            }
        } catch(Throwable e){
        }
        return isValid;
    }

    public static <T> T convertStringToObject(String jsonString,Class<T> clazz) {
        if(jsonString == null) {
            return null;
        }
        try {
            return new ObjectMapper().readValue(jsonString, clazz);
        } catch (Throwable e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    public static String convertObjectToString(Object object) {
        if(object == null) {
            return null;
        }
        try {
            return new ObjectMapper().writeValueAsString(object);
        } catch (Throwable e) {
            System.out.println(e.getMessage());
        }
        return null;
    }
}